<?php

include_once dirname(__FILE__) . '/Db.php';

class department {

    public $department_id;
    public $department_name;
    private $db;

    public function __construct() {
        $this->db = Db::get_instance();
    }

    public static function is_name_exit($DepName) {

        $sql = "SELECT COUNT(*) AS number FROM fac_department WHERE department_name='$DepName'";
        $result = Db::get_instance()->query($sql);
        $result[0]['number'];
        if ($result[0]['number'] > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    //插入
    function department_insert($DepName, $sort, $password) {
        if (department::is_name_exit($DepName)) {
            return 0;
        } else {
            $insert = "INSERT INTO fac_department (department_name,add_time,sort) VALUES('$DepName',NOW(),$sort);";
            $dept = $this->db->query($insert);
            if ($dept > 0) {
                // 创建用户
                $password = strtolower(hash('sha256', $password));
                $uid = $this->db->query("INSERT INTO fac_users (user_name,user_password,user_type_id) value ('$DepName','$password',4)");
                $this->db->query("INSERT INTO fac_user_department (user_id,department_id) value ('$uid','$dept');");
                return $uid;
            } else {
                return false;
            }
        }
    }

    //更新
    function department_update($DepId, $DepName, $sort, $password) {
        $update = "update `fac_department` set department_name='$DepName',sort = $sort where department_id=$DepId";
        if ($password != "") {
            $uid = Db::get_instance()->query("SELECT user_id FROM fac_user_department WHERE department_id = $DepId LIMIT 1;");
            $ret1 = $this->db->query($update);
            if ($uid[0]['user_id'] > 0) {
                $uid = intval($uid[0]['user_id']);
                $password = strtolower(hash('sha256', $password));
                $ret2 = Db::get_instance()->query("UPDATE `fac_users` SET user_password = '$password' WHERE user_id = $uid;");
            }
            return $ret1 || $ret2;
        } else {
            return $this->db->query($update);
        }
    }

    //删除
    function department_delete($DepId) {
        $uids = Db::get_instance()->query("SELECT user_id FROM fac_user_department WHERE department_id = $DepId;");
        Db::get_instance()->query("DELETE from fac_user_department WHERE department_id = $DepId;");
        foreach ($uids as $uid) {
            Db::get_instance()->query('DELETE from fac_users where user_id=' . $uid['user_id']);
        }
        return Util::dbDelete('fac_department', 'department_id', $DepId);
    }

    /**
     * 
     * @param type $DepId
     */
    function department_view_one($DepId) {
        $view = "select * from fac_department where department_id=$DepId";
        $row = $this->db->query($view);
        $this->department_id = $row[0]['department_id'];
        $this->department_name = $row[0]['department_name'];
    }

    function department_view_all($where = "") {
        return $this->db->query("SELECT
	*, (
		SELECT
			count(id)
		FROM
			`fac_order_department_mess`
		WHERE
			`fac_order_department_mess`.department_id = `fac_department`.department_id
	) AS wcount,
	(
		SELECT
			COUNT(*)
		FROM
			`fac_user_department`
		WHERE
			`fac_user_department`.department_id = `fac_department`.department_id
	) AS ucount,
	(
		SELECT
			COALESCE (
				(
					SUM(product_yes) / SUM(product_sum)
				) * 100,
				0
			)
		FROM
			`fac_order_department_mess`
		WHERE
			`fac_order_department_mess`.department_id = `fac_department`.department_id
	) AS rate
FROM
	fac_department
WHERE
	`hidden` = 'no'$where ORDER BY `sort` ASC;");
    }

    /**
     * 获取用户对应的department
     * @param type $uid
     */
    public static function getUserDepartment($uid) {
        $res = Db::get_instance()->query("SELECT department_id FROM `fac_user_department` WHERE `user_id` = $uid;");
        return intval($res[0]['department_id']);
    }

    /**
     * 根据department_id获取生产记录
     * @param type $department_id
     * @return type
     */
    public static function getDepProRecord($department_id) {
        $sql = "SELECT t1.*,t2.product_model,t2.gongyi FROM fac_department_product_record t1 "
                . "LEFT JOIN fac_product_mess t2 ON t1.product_id=t2.product_id  WHERE t1.department_id=$department_id";
        return Db::get_instance()->query($sql);
    }

    /**
     * 根据department_id获取取料记录
     * @param type $department_id
     * @return type
     */
    public static function getDepRecRecord($department_id) {
        $sql = "SELECT t1.*,t2.product_model,t2.gongyi FROM fac_department_receive_record t1 "
                . "LEFT JOIN fac_product_mess t2 ON t1.product_id=t2.product_id  WHERE t1.department_id=$department_id";
        return Db::get_instance()->query($sql);
    }

    /**
     * 车间库存是否存在
     * @param type $department_id
     * @param type $product_id
     * @return type
     */
    public static function isExistPro($department_id, $product_id) {
        $sql = "SELECT * FROM fac_department_storehouse WHERE department_id=$department_id AND product_id = $product_id";
        $ret = Db::get_instance()->query($sql);
        if ($ret[0]['id'] > 0)
            return true;
        else {
            return false;
        }
    }

    /**
     * 车间生产录入
     * @param type $department_id
     * @param type $product_id
     * @param type $number
     * @return type
     */
    public static function saveDepPro($department_id, $product_id, $number, $wnumber, $order_id) {
        $sql1 = "INSERT INTO fac_department_product_record(department_id, product_id, number, wnumber, create_time, order_id) VALUES ($department_id, $product_id, $number, '$wnumber', now(), $order_id);";
        #echo $sql1;
        if (department::isExistPro($department_id, $product_id)) {
            $sql2 = "UPDATE fac_department_storehouse SET finish_number=finish_number+$number WHERE department_id=$department_id AND product_id=$product_id;";
        } else {
            $sql2 = "INSERT INTO fac_department_storehouse(department_id, product_id, finish_number) VALUES($department_id, $product_id, $number);";
        }
        $ret1 = Db::get_instance()->query($sql1);
        $ret2 = Db::get_instance()->query($sql2);
        $dept = Db::get_instance()->query("SELECT * FROM fac_department WHERE department_id = $department_id;");
        if ($dept[0]['is_first'] == 0) {
            if ($dept[0]['unfinish_number'] >= $number) {
                $update = "UPDATE fac_department_storehouse SET unfinish_number = unfinish_number - $number WHERE department_id=$department_id AND product_id=$product_id;";
            } else {
                $update = "UPDATE fac_department_storehouse SET unfinish_number = 0 WHERE department_id=$department_id AND product_id=$product_id;";
            }
        } else {
            $update = "UPDATE fac_department_storehouse SET unfinish_number = 0 WHERE department_id=$department_id AND product_id=$product_id;";
        }
        Db::get_instance()->query($update);
        return $ret1 + $ret2;
    }

    /**
     * 车间领取录入
     * @param type $department_id
     * @param type $product_id
     * @param type $number
     * @return type
     */
    public static function saveDepRec($from_department_id, $department_id, $product_id, $number, $wnumber, $order_id) {
        $sql1 = "INSERT INTO fac_department_receive_record(department_id, from_department_id, product_id, number, wnumber, create_time, order_id) VALUES ($department_id, $from_department_id, $product_id, $number, '$wnumber', now(), $order_id);";
        if (department::isExistPro($department_id, $product_id)) {
            $sql2 = "UPDATE fac_department_storehouse SET finish_number=finish_number-$number WHERE department_id=$from_department_id AND product_id=$product_id;";
            $sql2.= "UPDATE fac_department_storehouse SET unfinish_number=unfinish_number+$number WHERE department_id=$department_id AND product_id=$product_id;";
        } else {
            $sql2 = "INSERT INTO fac_department_storehouse(department_id, product_id, unfinish_number) VALUES($department_id, $product_id, $number);";
        }
        $ret1 = Db::get_instance()->query($sql1);
        $ret2 = Db::get_instance()->query($sql2);
        return $ret1;
    }

    /**
     * 删除生产记录
     * @param type $id 记录id
     * @return type
     */
    public static function delDepPro($id) {
        $sql = "SELECT * FROM fac_department_product_record WHERE id = $id;";
        $ret = Db::get_instance()->query($sql);
        $department_id = $ret[0]['department_id'];
        $product_id = $ret[0]['product_id'];
        $number = $ret[0]['number'];
        $sql = "DELETE FROM fac_department_product_record WHERE id = $id;";
        $sql.= "UPDATE fac_department_storehouse SET unfinish_number=unfinish_number+$number WHERE department_id=$department_id AND product_id=$product_id;";
        $sql.= "UPDATE fac_department_storehouse SET finish_number=finish_number-$number WHERE department_id=$department_id AND product_id=$product_id;";
        return Db::get_instance()->query($sql);
    }

    /**
     * 删除领取记录
     * @param type $id 记录id
     * @return type
     */
    public static function delDepRec($id) {
        $sql = "SELECT * FROM fac_department_receive_record WHERE id = $id;";
        $ret = Db::get_instance()->query($sql);
        if ($ret > 0) {
            $department_id = $ret[0]['department_id'];
            $from_department_id = $ret[0]['from_department_id'];
            $product_id = $ret[0]['product_id'];
            $number = $ret[0]['number'];
            $sql = "DELETE FROM fac_department_receive_record WHERE id = $id;";
            $sql.= "UPDATE fac_department_storehouse SET unfinish_number=unfinish_number-$number WHERE department_id=$department_id AND product_id=$product_id;";
            $sql.= "UPDATE fac_department_storehouse SET finish_number=finish_number+$number WHERE department_id=$from_department_id AND product_id=$product_id;";
            return Db::get_instance()->query($sql);
        } else {
            return 0;
        }
    }

    public static function getGList($dept, $month = false) {
        return Db::get_instance()->query("SELECT
	fr.create_time,
	fm.product_model,
        fm.gongyi,
	fr.number,
	fd.department_name,
	fr.id,
        pd.product_order_code,
        fr.wnumber
FROM
	`fac_department_receive_record` fr
LEFT JOIN fac_product_mess fm ON fr.product_id = fm.product_id
LEFT JOIN fac_department fd ON fd.department_id = fr.from_department_id
LEFT JOIN fac_product_order pd ON pd.product_order_id = fr.order_id
WHERE
	fr.department_id = $dept AND pd.order_state <> '已完成' ORDER BY create_time DESC;");
    }

    public static function getPList($dept, $month = false) {
        return Db::get_instance()->query("SELECT
	fr.create_time,
	fm.product_model,
        fm.gongyi,
	fr.number,
	fr.id,
        pd.product_order_code,
        fr.wnumber
FROM
	`fac_department_product_record` fr
LEFT JOIN fac_product_mess fm ON fr.product_id = fm.product_id
LEFT JOIN fac_product_order pd ON pd.product_order_id = fr.order_id
WHERE
	fr.department_id = $dept AND pd.order_state <> '已完成' ORDER BY create_time DESC;");
    }

    /**
     * 获取是否第一个车间 开料
     * @param type $dept
     */
    public static function isFirstDept($dept) {
        $r = Db::get_instance()->query("SELECT * FROM `fac_department` WHERE `department_id` = $dept AND is_first = 1;");
        return $r ? true : false;
    }

}
